package com.zhende.hr.controller;

import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.zhende.hr.constant.Constans;
import com.zhende.hr.entity.LoginRequest;
import com.zhende.hr.entity.User;
import com.zhende.hr.mapper.oaview.OutAuthDao;
import com.zhende.hr.utils.JWTUtils;
import com.zhende.hr.utils.JwtTokenProvider;
import com.zhende.hr.utils.R;


/**
 * 获取token，访问接口，或者跳转oa
* @Package com.zhende.out.web 
* @Description: TODO(用一句话描述该文件做什么) 
* @author fmf   
* @date 2023年11月13日 下午12:34:01 
* @version V1.0
 */
@RestController
@RequestMapping("/u")
@CrossOrigin
public class TokenController {
	public static Logger log = LoggerFactory.getLogger(TokenController.class);
	@Autowired
	private OutAuthDao outAuthDao; 
	 @Autowired
	 private AuthenticationManager authenticationManager;
	 @Autowired
	 private JwtTokenProvider jwtTokenProvider;

	    @PostMapping("/login")
	    public R login(@RequestBody LoginRequest loginRequest) {
	        try {
	        	log.info("loginRequest="+loginRequest);
	        	
	            // 通过 Spring Security 认证用户的账号密码
	            Authentication authentication = authenticationManager.authenticate(
	                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
	            );

	            // 认证成功后生成 JWT Token
	            String token = jwtTokenProvider.generateToken(authentication);

	            // 返回 Token 给前端
	            R r = R.ok();
	            r.put("token", token);
	            
	            return r;

	        } catch (BadCredentialsException e) {
	            // 如果认证失败，返回 401
	            return R.error("账号密码错误");
	        }
	    }
	
	    
	
	    
	
	@RequestMapping("/getToken")
	public R getToken(@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "password", required = false) String password) {
		if (StringUtils.isBlank(name) || StringUtils.isBlank(password) || name.length() > 10
				|| password.length() > 10) {
			return R.error("账号密码错误");
		}
		User user = outAuthDao.getUsers(name, password);
		if (user == null) {
			return R.error("账号密码错误");
		}

		Map<String, String> map = new Hashtable<>();
		map.put("type", Constans.auth_INTERFACE);
		map.put("uuid", user.getUuid());
		map.put("time", String.valueOf(System.currentTimeMillis()));
		String token = JWTUtils.getToken(map);
		return R.ok(token);
	}
	
	public static void main(String[] args) {
        // 1. 创建 BCryptPasswordEncoder 对象
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        // 2. 明文密码
        String rawPassword = "Zd#yxt2025";  // 替换成你想要加密的密码

        // 3. 加密明文密码
        String encryptedPassword = passwordEncoder.encode(rawPassword);

        // 4. 输出加密后的密码
        System.out.println("Encrypted password: " + encryptedPassword);
		for (int i =0;i<10;i++) {
			System.out.println(UUID.randomUUID().toString().replaceAll("-", ""));
		}
		System.out.println(System.nanoTime());
		System.out.println(System.nanoTime());
		System.out.println(System.currentTimeMillis());
		
		System.out.println(System.currentTimeMillis());
		String name = "aa";
		String password = "bb";
		Map<String, String> map = new Hashtable<>();
		map.put("type", Constans.auth_INTERFACE);
		map.put("uuid", UUID.randomUUID().toString());  // 添加唯一标识符
		map.put("name", name);
//		map.put("password", password);
		map.put("time", String.valueOf(System.currentTimeMillis()));
		String token = JWTUtils.getToken(map);
		System.out.println(token);
		map.put("uuid", UUID.randomUUID().toString());  // 添加唯一标识符
		map.put("time", String.valueOf(System.currentTimeMillis()+3333333l));
		token = getToken(map);
		System.out.println(token);
	}
    private static final String SING = "fmf123456";
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        //默认7天过期
        instance.add(Calendar.HOUR,2);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

	
}
